//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
      content:{},
      input_mark:'',
      _id:'',
      options:{},
      userInfo:{},
      inputValue:'',
      userId:''
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function (options) {
    console.log('onLoad')
    var that = this;
    that.setData({
        _id:options.id,
        options:options
    });
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo){
      console.log(userInfo)
      //更新数据
      that.setData({
        userInfo:userInfo
      })
    });
    this.getOpenID();
    this.fetchData(options.id);
  },
  // 用户通过键盘输入值时，就会触发这个函数
  inputMark:function(input){
    var that = this;
    console.log(input);
    // 缓存用户输入的值,注意这里一次只能修改一个值
    that.setData({
      input_mark:input.detail.value
    });
  },
  //提交评论
  submitMark:function(){
    var that = this;
     wx.request({
        url: app.URL+'/edit_mark',
        data:{
          id:that.data._id,
          content:that.data.input_mark,
          userId:that.data.userId,
          userName:that.data.userInfo.nickName,
          userIcon:that.data.userInfo.avatarUrl
        },
        success: function (res) {
          if(res.statusCode ==200){
           that.onLoad(that.data.options);
           that.setData({
               inputValue:''
           });
            wx.showToast({
                title: '评论成功！',
                icon: 'success',
                duration: 3000
            });
          } else{
            wx.showToast({
                title: '出错了，请稍后再试..',
                icon: 'fail',
                duration: 3000
            });
          }
        }
     })
  },
  fetchData:function(id){
    var that = this
    console.log(id);
    wx.request({
      url: app.URL+'/get_info_byId?id='+id,
      success: function (res) {
        if(res.statusCode ==200){
        console.log(res);
        var theTime = new Date(res.data[0].time);
        res.data[0].date = theTime.getFullYear()+'-'+(theTime.getMonth()+1)+'-'+theTime.getDate();;
        that.setData({
             content:res.data[0]
          });
        }else{
          console.log('error')
        }
      }
    });
  },
  getOpenID:function(){
    var that = this;
    wx.login({
      success: (res)=>{
        console.log(res.code);
        wx.request({
           url:'https://api.weixin.qq.com/sns/jscode2session?appid=wxf89f318b1e769832&secret=38f45a85816ef2f9508f9b2c58adfa81&js_code='+res.code+'&grant_type=authorization_code',
           success:function(data){
              console.log(data.data.openid)
              that.setData({
                  userId:data.data.openid
              });
           }
         })
      },
    })
  }
})
